package org.swim.web.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.swim.remote.entities.INotification;
import org.swim.remote.exceptions.SwimException;
import org.swim.web.servlet.consts.Action;
import org.swim.web.utils.SwimUtils;

public class NotificationSL extends SwimServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doRequest(HttpServletRequest request,
			HttpServletResponse response, Method method, Action action)
			throws ServletException, IOException {
		switch (action) {
		default:
			try {
				getLastNotification(request, response);
			} catch (SwimException e) {
				e.printStackTrace();
			}
			break;
		}

	}

	private void getLastNotification(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException, SwimException {
		List<INotification> notifications = new ArrayList<INotification>();
		
		if(SwimUtils.isLogged(request) && request.getParameterMap().containsKey("lastNotificationTS")){
			Date lastNot = new Date(Long.parseLong(request.getParameter("lastNotificationTS")));
			JSONObject object = new JSONObject();
			object.accumulate("token", getToken(request));
			
			@SuppressWarnings("unchecked")
			List<INotification> allNots = (List<INotification>)request.getAttribute("notifications");
			for (INotification iNotification : allNots) {
				if(iNotification.getTimestamp().after(lastNot)){
					notifications.add(iNotification);
				}
			}
		}
		request.setAttribute("notifications", notifications);
		request.getRequestDispatcher("include/notification-item.jsp").forward(request,
				response);
		
	}
}
